<?php
namespace App\Http\Controllers\Admin;

use App\Events\ActivateUser;
use App\Events\RegSuccess;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\MConfig;
use App\Models\MLog;
use App\Models\MUser;
use App\Templates\ActivationUserAct;
use App\Templates\RegUserAct;
use App\Utils\ComUtil;
use DB;
use Exception;
use Illuminate\Http\Request;
use ReflectionClass;

/**
 * 系统设置控制器
 */
class SettingController extends Controller
{
    use RegUserAct, ActivationUserAct;

    /**
     * 网站信息配置界面
     */
    public function settingPage()
    {
        return view("admin.web_setting");
    }

    /**
     * 系统配置信息项保存
     */
    public function configSave(Request $request)
    {
        //例外配置项列表，此列表内的元素不存储
        $except = ["_title", "_token"];

        if (MConfig::saveAttr($request->_title, $request->except($except))) {
            $this->data = $this->makeJsCode(0, "保存成功！");
        } else {
            $this->data = $this->makeJsCode(1, "保存失败！");
        }
        return response()->json($this->data);
    }

    /**
     * 系统操作日志列表
     */
    public function logsPage(Request $request, $index = 1)
    {
        //初始化分页
        $this->fyInit(route("admin.logs"), 15, $request->getQueryString());
        $query = (new MLog())->query();

        //按条件筛选
        if ($request->has(['search_type', 'search_str_1'])) {
            if ($request->search_type == 1) { //管理员搜索(精确搜索)
                $query = $query->where('username', $request->search_str_1);
            } elseif ($request->search_type == 2) {  //ip地址搜索(精确搜索)
                $query = $query->where('ip', $request->search_str_1);
            }

        }elseif($request ->has(['search_type','search_str_2'])){

            if ($request->search_type == 3) {  //按模块搜素
                $query = $query->where('module', $request->search_str_2);
            }
        }
        $this->fyCalc($query->count(), $index);
        $this->data['logs'] = $query->orderBy('time', 'desc')
            ->skip($this->fy_pgOffset)->take($this->fy_pgSize)
            ->get();

        //分页视图初始化
        $this->fyViewInit($this->data);
        return view('admin.logs')->with($this->data);
    }

    /**
     * 日志删除处理
     */
    public function logsDel($id)
    {
        Mlog::destroy($id);
        $this->data = $this->makeJsCode(0, "删除成功！");
        return back()->with($this->data);
    }

    /**
     * 登录界面皮肤列表
     */
    public function loginThemeList(Request $request)
    {
        $this->data['themes'] = config("logintheme.list");
        return view("admin.login-theme")->with($this->data);
    }

    /**
     *  登录界面切换皮肤请求
     */
    public function loginThemeAct($key)
    {
        if (MConfig::saveAttr("theme", ['name' => $key])) {
            $this->data = $this->makeJsCode(0, "更换主题成功！");
        } else {
            $this->data = $this->makeJsCode(1, "更换主题失败！");
        }
        return back()->with($this->data);
    }

    /**
     *  一键初始化页面
     */
    public function initialPage()
    {
        $class = new ReflectionClass(Muser::class);
        dd(DB::table()->first());
        return view('admin.initial');
    }

    /**
     * 一键初始化方法
     */
    public function initialAct(Request $request)
    {

        if (!$this->validateReq($request, Admin::initialRulesWithMsg(0), Admin::initialRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

        $admin = Admin::where('username', ss('admin_name'))
            ->where('userpass', md5($request->adminpass))->first();

        if (empty($admin)) {
            $this->data = $this->makeJsCode(1, '管理员密码错误!');
            return response()->json($this->data);
        }

        //权限审查判断
        if (!$admin->rolesCan('permission.initial')) {
            $this->data = $this->makeJsCode(1, '管理员没有此权限!');
            return response()->json($this->data);
        }

        if (Admin::initalSystem($request)) {
            $this->data = $this->makeJsCode(0, "初始化成功！");
        } else {
            $this->data = $this->makeJsCode(1, "初始化失败，请重新尝试！");
        }

        return response()->json($this->data);
    }

    /**
     * 一键测试页面
     */
    public function systemTestPage()
    {
        return view("admin.system_test");
    }

    /**
     * 一键测试功能实现
     */
    public function systemTest(Request $request)
    {
        if (!$request->has(['num', 'pass']) || $request->num <= 0) {
            $this->data = $this->makeJsCode(1, "请提交完整的表单数据！");
            return response()->json($this->data);
        }

        $admin = Admin::where('username', ss('admin_name'))
            ->where('userpass', md5($request->pass))->first();
        if (empty($admin)) {
            $this->data = $this->makeJsCode(1, "管理员密码输入错误! ");
            return response()->json($this->data);
        }

        //验证当前管理员是否有权限操作
        if (!$admin->rolesCan('permission.test')) {
            $this->data = $this->makeJsCode(1, "您没有此权限! ");
            return response()->json($this->data);
        }

        //如果有用户存在（除根节点），则不可进行测试操作
        if (MUser::count() != 1) {
            $this->data = $this->makeJsCode(1, "请一键初始化之后再进行奖金测试！");
            return response()->json($this->data);
        }
        try {
            DB::transaction(function () use ($request) {
                for ($i = 1; $i <= $request->num; $i++) {
                    $user = MUser::randomUser(10000 + $i);
                    if (!empty($user)) {
                        event(new RegSuccess($user));   //发送注册成功事件通知
                        if (!$user->activation($bdzx = null,$ok_type=1)) {
//                            event(new ActivateUser($user)); //发送激活成功事件通知
                            $this->data = $this->makeJsCode(1, "自动测试失败，请重新尝试！");
                        }
                    }
                }
                $this->data = $this->makeJsCode(0, "测试成功，请检查奖金！");
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "自动测试失败，请重新尝试！");
        }
        return response()->json($this->data);
    }
}